package crawler;
import java.util.*;

public class ConsoleWebCrawler {
    private Scanner scanner = new Scanner(System.in);
    private UserManager userManager = new UserManager();
    private WebCrawler webCrawler = new WebCrawler();
    private DataStorage dataStorage = new DataStorage();
    private String currentUser;

    String option ;


    public static void main(String[] args) {
        new ConsoleWebCrawler().run();
    }
//循环显示菜单
    private void run() {
        while (true) {
            //currentUser == null 说明没登录进入登录菜单，反之进入功能菜单
            if (currentUser == null) {
                showLoginMenu();
            } else {
                showMainMenu();
            }
        }
    }
//登录菜单
    private void showLoginMenu() {
        System.out.println("1. 登录");
        System.out.println("2. 注册");
        System.out.println("3. 退出");
        System.out.print("请选择: ");
//根据输入选择执行指令
        switch (scanner.nextLine()) {
            case "1":
            {
                //进入登录的方法
                handleLogin();
                break;
            }
            case "2":
            {
                //进入注册的方法
                handleRegister();
                break;
            }
            case "3":
            {
                //退出
                System.exit(0);

            }
            default:
            {
                //防止非法输入
                System.out.println("无效选项");
            }
        }
    }
//登录后的功能菜单
    private void showMainMenu() {
        System.out.println("1. 爬取网页");
        System.out.println("2. 查看历史");
        String status = null;
        try{
            if(userManager.isRemember(currentUser)){
                status = "已记住";
            }else{
                status = "未记住";
            }
            System.out.println("3. 记住密码("+ status +")");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println("4. 退出登录");
        System.out.print("请选择: ");

//根据输入选择进入方法
        switch (scanner.nextLine()) {
            case "1":
            {
                //进入handleCrawl方法，爬取网页
                handleCrawl();
                break;
            }
            case "2":
            {
                //进入handleHistory方法，查看历史记录
                handleHistory();
                break;
            }
            case "4":
            {
                //登录时currentUser被赋值，现在改为null，通过run判断后返回登录菜单
                currentUser = null;
                break;
            }
            case "3":
            {
                try
                {
                    if(status.equals("未记住")){
                        userManager.rememberPassword(currentUser);
                        System.out.println("已记住，下次登陆无需密码");
                    }else if(status.equals("已记住")){
                        userManager.cancelRemember(currentUser);
                        System.out.println("已取消，下次登陆需要密码");
                    }
                } catch (Exception e) {
                    System.out.println("意外错误：" + e.getMessage());
                }
                break;
            }
            default:
            {
                System.out.println("无效选项");
            }
        }
    }
//爬取网页方法实现
    private void handleCrawl() {
        //希望增加：判断URL的合法性再访问
        try {
            //通过调用scanner方法获取URL
            System.out.print("请输入URL: ");
            String url = scanner.nextLine();
            //调用实例的webCrawler对象
            CrawlResult result = webCrawler.crawl(url);
            //结合webBrawler返回的CrawlResult打印结果
            System.out.println("标题: " + result.getTitle());
            System.out.println("发现链接" + result.getLinks().size() + "个:");
            result.getLinks().forEach(System.out::println);

            while(true){
                //实现选择是否保存
                System.out.print("是否保存结果？(y/n): ");
                option = scanner.nextLine();
                switch(isTrue(option)){
                    case "y":{
                        // 询问是否需要更改文件名
                        System.out.print("是否需要更改文件名？(y/n): ");
                        String filename = null;
                        option = scanner.nextLine();
                        while(true){
                            switch(isTrue(option)){
                                case "y":{
                                    System.out.print("请输入新的文件名: ");
                                    filename = scanner.nextLine();
                                    break;
                                }
                                case"n":{
                                    break;
                                }
                                case "x":{
                                    System.out.print("输入无效，请重新确认你的选择");
                                    continue;
                                }
                            }
                            break;
                        }
                        //调用dataStorage的saveData来实现保存
                        dataStorage.saveData(currentUser, result,filename);
                        System.out.println("保存成功！");
                        break;
                    }
                    case "n":{
                        break;
                    } case "x":{
                        System.out.println("输入无效，请重新确认你的选择：");
                        continue;
                    }
                }
                break;
            }
        } catch (Exception e) {
            System.out.println("爬取失败: " + e.getMessage());
        }
    }
//查询历史记录
    private void handleHistory() {
        try {
            List<String> files = dataStorage.listHistory(currentUser);
            if (files.isEmpty()) {
                System.out.println("无历史记录");
                return;
            }

            System.out.println("历史记录:");
            for (int i = 0; i < files.size(); i++) {
                System.out.println((i+1) + ". " + files.get(i));
            }

            System.out.print("输入编号查看详情或0返回）: ");
            int choice = Integer.parseInt(scanner.nextLine());
            if (choice > 0 && choice <= files.size()) {
                String content = dataStorage.getHistoryContent(currentUser, files.get(choice-1));
                System.out.println(content);
                System.out.println("1. 改名");
                System.out.println("2. 删除记录");
                System.out.println("3. 返回");
                System.out.print("请选择: ");
                int option = Integer.parseInt(scanner.nextLine());
                switch (option) {
                    case 1:
                    {
                        System.out.print("请输入新的文件名: ");
                        String newFilename = scanner.nextLine();
                        dataStorage.renameFile(currentUser, files.get(choice - 1), newFilename);
                        break;
                    }
                    case 2:
                    {
                        dataStorage.deleteFile(currentUser, files.get(choice - 1));
                        break;
                    }
                    case 3:
                    {
                        break;
                    }
                    default:
                    {
                        System.out.println("无效选项");
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("查询失败: " + e.getMessage());
        }
    }

    //处理登录和注册的方法
    //希望增加：
    //1、修改用户密码、用户名
    //2、注销账户
    //3、记住密码
    //4、管理员模式
    private void handleLogin() {
        try {

            System.out.print("请输入用户名: ");
            String username = scanner.nextLine();
            if(!userManager.isRemember(username)){
                System.out.print("请输入密码: ");
                String password = scanner.nextLine();
                if(userManager.login(username, password)){
                    currentUser = username;
                    System.out.println("登录成功！");
                }else {
                    System.out.println("用户名或密码错误！");
                }
            } else if(userManager.isRemember(username)){
                currentUser = username;
                System.out.println("登录成功！");
            }
        } catch (Exception e) {
            System.out.println("登录出错: " + e.getMessage());
        }
    }

    private void handleRegister() {
        try {
            System.out.print("请输入用户名: ");
            String username = scanner.nextLine();
            System.out.print("请输入密码: ");
            String password = scanner.nextLine();
            if (userManager.register(username, password)) {
                System.out.println("注册成功！");
            } else {
                System.out.println("用户名已存在！");
            }
        } catch (Exception e) {
            System.out.println("注册出错: " + e.getMessage());
        }
    }

    private String isTrue(String option){
        if(option.equalsIgnoreCase("y")){
            return "y";
        } else if (option.equalsIgnoreCase("n")) {
            return "n";
        }else{
            return "x";
        }
    }
}
